package com.xzp.springboot_in_action.controller;


import com.xzp.springboot_in_action.entity.Book;
import com.xzp.springboot_in_action.repository.ReadingListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller   //这样组件扫描会自动将其注册为Spring应用程序上下文里的一个Bean
@RequestMapping("/book")
public class ReadingListController {

    @Autowired
    private ReadingListRepository readingListRepository;

    @GetMapping(value = "/{reader}")
    public String readersBooks(@PathVariable("reader") String reader,Model model){  //使用模板的方式，映射视图解析

        List<Book> readingList = readingListRepository.findByReader(reader);
        if (readingList != null){
            model.addAttribute("books",readingList);
        }

        return "readingList";  //返回逻辑视图名
    }

    @PostMapping(value = "/{reader}")
    public String addToReadingList(@PathVariable("reader") String reader,Book book) {
        book.setReader(reader);
        readingListRepository.save(book);
        return "redirect:/book/{reader}";  //重定向
    }
}
